using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Odbc;
using System.Data.Common;
using System.Globalization;
using ResourceBlender.DAL;

public partial class Generate : LocalPage 
{
    //TODO: add "Select your lang", universal strings included in all resources

    /// <summary>
    /// Shows a form for generating resources or an XML spreadsheet
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            try {
                litAddAppLink.Text = Utils.FormatLink(Resources.UIStrings.AddAppLink, ResolveUrl("~/Applications.aspx"));
                IDictionary<string, string> templates = ResourceBlenderDAL.GetResourceGenerationTypes();
                foreach(KeyValuePair<string, string> resourceType in templates) {
                    ListItem itm = new ListItem(resourceType.Key, resourceType.Value);
                    itm.Attributes.Add("class", resourceType.Value);
                    radFormat.Items.Add(itm);
                }
                if(appSelector.Applications.Count > 0) {
                    mltNoApplications.ActiveViewIndex = 1;
                }
                txtThreshold.Text = Constants.DefaultThreshold.ToString();
            } catch(Exception ex) {
                mltNoApplications.ActiveViewIndex = 2;
                lblErrorDescription.Text = ex.Message;
            }
        }
        lblBundleError.Visible = false;
    }

    /// <summary>
    /// Processes the request and generates the output
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnGenerate_Click(object sender, EventArgs e) {
        Page.Validate();
        if(!Page.IsValid) {
            return;
        }
        try {
            string applicationId = appSelector.SelectedApplicationID;
            int threshold = int.Parse(txtThreshold.Text);
            bool includeSummary = chkIncludeSummary.Checked,
                 escapeUnicode = chkEscapeUnicode.Checked;
            string[] bundles = appSelector.SelectedBundles.ToArray(),
                     languages = appSelector.SelectedLanguages.ToArray();
            RBApplication app = null;
            try {
                app = ResourceBlenderDAL.GetApplication(applicationId, true);
            } catch(Exception ex) {
                throw new ArgumentException(Resources.Errors.CouldNotLoadApplData + ":" + ex.Message);
            }
            //if(radFormat.SelectedIndex < Enum.GetValues(typeof(Constants.ResourceType)).Length) {
            try {
                Constants.ResourceType type = (Constants.ResourceType)Enum.Parse(typeof(Constants.ResourceType), radFormat.SelectedValue);
                switch(type) {
                    case Constants.ResourceType.Firefox:
                        bool hasXUL = app.Bundles.Any(b => b.Value.ToLower() == "xul"),
                             hasJS = app.Bundles.Any(b => b.Value.ToLower() == "javascript");
                        if(hasXUL && hasJS) {
                            ResourceGenerator.GenerateFirefox(app.ApplicationName, applicationId, threshold, bundles, languages, app.DefaultLanguage, includeSummary);
                        } else {
                            lblBundleError.Text = Resources.Errors.FirefoxBundlesMissing;
                            lblBundleError.Visible = true;
                        }
                        break;
                    case Constants.ResourceType.Java:
                        ResourceGenerator.GenerateJava(app.ApplicationName, applicationId, threshold, bundles, languages, app.DefaultLanguage, includeSummary, escapeUnicode);
                        break;
                    case Constants.ResourceType.DotNet:
                        ResourceGenerator.GenerateDotNet(app.ApplicationName, applicationId, threshold, bundles, languages, app.DefaultLanguage, includeSummary, false);
                        break;
                    case Constants.ResourceType.DotNetCF:
                        ResourceGenerator.GenerateDotNet(app.ApplicationName, applicationId, threshold, bundles, languages, app.DefaultLanguage, includeSummary, true);
                        break;
                    case Constants.ResourceType.PO:
                        ResourceGenerator.GeneratePO(app.ApplicationName, applicationId, threshold, bundles, languages, app.DefaultLanguage, includeSummary);
                        break;
                    default:
                        throw new ArgumentException();
                }
            } catch {// not a preset, must be a custom format
                RBTemplate template = ResourceBlenderDAL.GetTemplate(radFormat.SelectedValue);
                KeyValuePair<string, Dictionary<string, Dictionary<string, Dictionary<string, RBTranslation>>>> rawResources = ResourceGenerator.GenerateBundles(app.DefaultLanguage, applicationId, threshold, bundles, languages, app.DefaultLanguage, includeSummary);
                ResourceGenerator.GenerateCustom(app.ApplicationName, rawResources, template.FileName, template.FileStart, template.FileEnd, template.FileLine);
            }
        } catch(Exception ex) {
            mltNoApplications.ActiveViewIndex = 2;
            lblErrorDescription.Text = ex.Message;
        }
    }


    /// <summary>
    /// Checks an output format has been selected
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
    protected void vldFormatRequired_ServerValidate(object sender, ServerValidateEventArgs e) {
        e.IsValid = radFormat.SelectedValue != null && radFormat.SelectedValue.Length > 0;
    }
}
